package com.htdz.controller;

import com.htdz.entity.Node;
import com.htdz.entity.Resource;
import com.htdz.entity.Role;
import com.htdz.entity.UsersInfo;
import com.htdz.service.ResourceService;
import com.htdz.service.RoleService;
import com.htdz.util.JsonUtil;
import com.htdz.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/base")
public class RoleController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	public RoleService roleService;
	@Autowired
	public RedisUtil redisUtil;

	@RequestMapping(value = "/listRole")
	public String listResource(HttpServletRequest request,Model model, Integer pageNum){
		if( pageNum == null ) pageNum = 1;
		Role role = new Role();
        List<Role> roleList = roleService.listRole(role,pageNum);
        model.addAttribute("roleList",roleList);
        //model.addAttribute("usersInfo",usersInfo);
		return "listRole";
	}

	@RequestMapping("/saveUsersRole")
	public String saveUsersRole(Model model,Long grantUsersId,String checkedIds){
		roleService.saveUsersRole(grantUsersId,checkedIds);
		return "redirect:/users/listUsers";
	}

	/**
	 *
	 * @param model
	 * @param grantUsersId
	 * @return
	 */
	@RequestMapping(value = "/listRoleTree")
	@ResponseBody
	public String listRoleTree(Model model,Long grantUsersId){
		Role role = new Role();
		List<Node> nodeList = roleService.listRoleTree(role,grantUsersId);
		logger.info(JsonUtil.obj2json(nodeList));
		return JsonUtil.obj2json(nodeList);
	}

    /**
     * 链接到添加角色页面
     * @param request
     * @param model
     * @return
     */
	@RequestMapping("/linkAddRole")
	public String linkAddRole(HttpServletRequest request,Model model){
		return "addRole";
	}

    /**
     * 增加角色名
     * @param request
     * @param model
     * @param roleName
     * @return
     */
    @RequestMapping("/saveRole")
    public String saveRole(HttpServletRequest request,Model model,String roleName){
        roleService.saveRole(roleName);
        return "redirect:/base/listRole";
    }

    /**
     * 删除角色
     * @param request
     * @param model
     * @param roleId
     * @return
     */
	@RequestMapping("/deleteRole")
	public String deleteRole(HttpServletRequest request,Model model,Long roleId){
		roleService.deleteRole(roleId);
		return "redirect:/base/listRole";
	}
}
